package com.atguigu.gmall.realtime.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ExecutionException;

public class RedisUtil {
    // 获取redis连接
    public static StatefulRedisConnection<String, String> getRedisAsyncConnection(){
        RedisClient redisClient = RedisClient.create("redis://hadoop102:6379");
        StatefulRedisConnection<String, String> asyncRedisConn = redisClient.connect();
        return asyncRedisConn;
    }
    //关闭redis连接
    public static void closeRedisAsyncConnection(StatefulRedisConnection<String, String> asyncRedisConn){
        if (asyncRedisConn != null){
            asyncRedisConn.close();
        }
    }
    //从redis获取数据
    public static JSONObject readDimAsync(StatefulRedisConnection<String,String> asyncRedisConn,String tableName,String id){
        String key = getKey(tableName, id);
        RedisAsyncCommands<String, String> async = asyncRedisConn.async();
        try {
            String dimJsonStr = async.get(key).get();
            if (StringUtils.isNotEmpty(dimJsonStr)){
                return JSON.parseObject(dimJsonStr);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }
    //向redis写入数据
    public static void writeDimAsync(StatefulRedisConnection<String,String> asyncRedisConn,String tableName,String id, JSONObject jsonObject){
        RedisAsyncCommands<String, String> async = asyncRedisConn.async();
        async.setex(getKey(tableName, id), 24*3600, jsonObject.toJSONString());
    }

    public static String getKey(String tableName, String id) {
        return tableName + ":" + id;
    }
}
